<template>
  <t-drawer
    :visible="internalVisible"
    :header="isEdit ? '编辑角色' : '新增角色'"
    size="600px"
    placement="right"
    :confirm-btn="{ content: '保存', loading: saveLoading }"
    @confirm="handleSave"
    @close="handleClose"
  >
    <t-form
      ref="roleForm"
      :data="formData"
      :rules="formRules"
      label-align="right"
      label-width="100px"
    >
      <t-form-item label="角色名称" name="roleName">
        <t-input v-model="formData.roleName" placeholder="请输入角色名称" maxlength="50" />
      </t-form-item>

      <t-form-item label="角色值" name="roleValue">
        <t-input
          v-model="formData.roleValue"
          placeholder="请输入角色值，如：admin, user"
          maxlength="50"
        />
      </t-form-item>

      <t-form-item label="状态" name="status">
        <t-select
          v-model="formData.status"
          placeholder="请选择状态"
          :popup-props="{ attach: 'body' }"
        >
          <t-option :value="1" label="启用" />
          <t-option :value="0" label="禁用" />
        </t-select>
      </t-form-item>

      <t-form-item label="备注" name="remark">
        <t-textarea
          v-model="formData.remark"
          placeholder="请输入备注信息"
          maxlength="200"
          :autosize="{ minRows: 3, maxRows: 5 }"
        />
      </t-form-item>

      <t-form-item label="菜单权限" name="menuPermissions">
        <div class="menu-permissions-container">
          <div class="menu-permissions-toolbar">
            <t-space>
              <t-button size="small" theme="default" @click="handleExpandAll">
                {{ expandAll ? '收起全部' : '展开全部' }}
              </t-button>
              <!-- <t-button size="small" theme="default" @click="handleCheckAll">
                {{ checkAll ? '取消全选' : '全选' }}
              </t-button> -->
              <t-button size="small" theme="default" @click="getMenuTreeData" :loading="menuLoading">
                刷新菜单
              </t-button>
            </t-space>
          </div>
          <div v-if="menuLoading" class="menu-loading">
            <t-loading size="small" text="加载菜单数据中..." />
          </div>
          <t-tree
            v-else
            ref="menuTree"
            :data="menuTreeData"
            :keys="treeKeys"
            :expanded.sync="expandedKeys"
            :value="checkedKeys"
            @change="handleTreeChange"
            checkable
            hover
            :check-strictly="false"
            :line="true"
          />
        </div>
      </t-form-item>
    </t-form>
  </t-drawer>
</template>

<script>
import {
  Drawer as TDrawer,
  Form as TForm,
  FormItem as TFormItem,
  Select as TSelect,
  Option as TOption,
  Input as TInput,
  Textarea as TTextarea,
  Tree as TTree,
  Button as TButton,
  Space as TSpace,
  Loading as TLoading
} from 'tdesign-vue';
import { getMenuList } from '@/api/menu';

export default {
  name: 'RoleFormDrawer',
  components: {
    TDrawer,
    TForm,
    TFormItem,
    TSelect,
    TOption,
    TInput,
    TTextarea,
    TTree,
    TButton,
    TSpace,
    TLoading
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    currentEditData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      saveLoading: false,
      menuLoading: false,
      expandAll: false,
      checkAll: false,
      expandedKeys: [],
      checkedKeys: [],

      // 树配置
      treeKeys: {
        value: 'id',
        label: 'label',
        children: 'children'
      },

      // 表单数据
      formData: {
        roleName: '',
        roleValue: '',
        status: 1,
        remark: '',
        menuPermissions: [],
      },

      // 表单验证规则
      formRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { max: 50, message: '角色名称不能超过50个字符', trigger: 'blur' },
        ],
        roleValue: [
          { required: true, message: '请输入角色值', trigger: 'blur' },
          { max: 50, message: '角色值不能超过50个字符', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_-]+$/, message: '角色值只能包含字母、数字、下划线和连字符', trigger: 'blur' },
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' },
        ],
        remark: [
          { max: 200, message: '备注不能超过200个字符', trigger: 'blur' },
        ],
      },

      // 菜单树数据
      menuTreeData: [],
    };
  },

  computed: {
    internalVisible: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit('update:visible', value);
      }
    }
  },

  watch: {
    visible(val) {
      if (val) {
        this.initFormData();
        this.getMenuTreeData();
      }
    }
  },

  methods: {
        // 获取菜单树数据
    async getMenuTreeData() {
      this.menuLoading = true;
      try {
        const response = await getMenuList();

        // 处理响应数据
        if (response.data && response.data.code === 200) {
          this.menuTreeData = this.transformMenuToTree(response.data.data || []);
        } else {
          // 如果后端还未实现，使用模拟数据
          this.menuTreeData = this.transformMenuToTree(this.getMockMenuData());
        }
      } catch (error) {
        // 出错时使用模拟数据
        this.menuTreeData = this.transformMenuToTree(this.getMockMenuData());
        this.$message.warning('获取菜单数据失败，使用模拟数据');
      } finally {
        this.menuLoading = false;
        // 菜单数据加载完成后，重新初始化树状态
        this.$nextTick(() => {
          this.initTreeState();
        });
      }
    },

    // 转换菜单数据为树结构
    transformMenuToTree(menuData) {
      const transform = (nodes) => {
        return nodes.map(node => {
          const menuType = node.type !== undefined ? node.type : this.convertMenuTypeToType(node.menuType);
          const typeLabel = this.getMenuTypeLabel(menuType);

          return {
            id: node.id,
            label: `${node.name || node.nodeName || '未命名菜单'} ${typeLabel}`,
            menuType: menuType,
            permission: node.permission || '',
            children: node.children && node.children.length > 0 ? transform(node.children) : []
          };
        });
      };

      return transform(menuData);
    },

    // 获取菜单类型标签
    getMenuTypeLabel(type) {
      const typeMap = {
        0: '(目录)',
        1: '(菜单)',
        2: '(权限)'
      };
      return typeMap[type] || '(未知)';
    },

    // 转换菜单类型
    convertMenuTypeToType(menuType) {
      // 前端原有的menuType: 1-目录, 2-菜单, 3-权限
      // 服务端的type: 0-目录, 1-菜单, 2-权限
      switch (menuType) {
        case 1:
          return 0; // 目录
        case 2:
          return 1; // 菜单
        case 3:
          return 2; // 权限
        default:
          return 1; // 默认为菜单
      }
    },

    // 模拟菜单数据（用于后端未实现时的fallback）
    getMockMenuData() {
      return [
        {
          id: 1,
          name: '系统管理',
          type: 0, // 目录
          path: '/system',
          icon: 'setting',
          children: [
            {
              id: 2,
              name: '用户管理',
              type: 1, // 菜单
              path: '/system/user',
              permission: 'system:user:view',
              icon: 'user',
              children: [
                {
                  id: 6,
                  name: '新增用户',
                  type: 2, // 权限
                  permission: 'system:user:add',
                  children: [],
                },
                {
                  id: 7,
                  name: '编辑用户',
                  type: 2, // 权限
                  permission: 'system:user:edit',
                  children: [],
                },
                {
                  id: 8,
                  name: '删除用户',
                  type: 2, // 权限
                  permission: 'system:user:delete',
                  children: [],
                },
                {
                  id: 9,
                  name: '查看用户',
                  type: 2, // 权限
                  permission: 'system:user:view',
                  children: [],
                },
              ],
            },
            {
              id: 3,
              name: '角色管理',
              type: 1, // 菜单
              path: '/system/role',
              permission: 'system:role:view',
              icon: 'user-setting',
              children: [
                {
                  id: 10,
                  name: '新增角色',
                  type: 2, // 权限
                  permission: 'system:role:add',
                  children: [],
                },
                {
                  id: 11,
                  name: '编辑角色',
                  type: 2, // 权限
                  permission: 'system:role:edit',
                  children: [],
                },
                {
                  id: 12,
                  name: '删除角色',
                  type: 2, // 权限
                  permission: 'system:role:delete',
                  children: [],
                },
                {
                  id: 13,
                  name: '查看角色',
                  type: 2, // 权限
                  permission: 'system:role:view',
                  children: [],
                },
              ],
            },
            {
              id: 4,
              name: '菜单管理',
              type: 1, // 菜单
              path: '/system/menus',
              permission: 'system:menu:view',
              icon: 'menu-fold',
              children: [
                {
                  id: 14,
                  name: '新增菜单',
                  type: 2, // 权限
                  permission: 'system:menu:add',
                  children: [],
                },
                {
                  id: 15,
                  name: '编辑菜单',
                  type: 2, // 权限
                  permission: 'system:menu:edit',
                  children: [],
                },
                {
                  id: 16,
                  name: '删除菜单',
                  type: 2, // 权限
                  permission: 'system:menu:delete',
                  children: [],
                },
                {
                  id: 17,
                  name: '查看菜单',
                  type: 2, // 权限
                  permission: 'system:menu:view',
                  children: [],
                },
              ],
            },
          ],
        },
        {
          id: 18,
          name: '运营管理',
          type: 0, // 目录
          path: '/operation',
          icon: 'tools',
          children: [
            {
              id: 19,
              name: '疾病管理',
              type: 1, // 菜单
              path: '/operation/disease',
              permission: 'operation:disease:view',
              icon: 'heart',
              children: [
                {
                  id: 20,
                  name: '新增疾病',
                  type: 2, // 权限
                  permission: 'operation:disease:add',
                  children: [],
                },
                {
                  id: 21,
                  name: '编辑疾病',
                  type: 2, // 权限
                  permission: 'operation:disease:edit',
                  children: [],
                },
                {
                  id: 22,
                  name: '删除疾病',
                  type: 2, // 权限
                  permission: 'operation:disease:delete',
                  children: [],
                },
              ],
            },
            {
              id: 23,
              name: '用户管理',
              type: 1, // 菜单
              path: '/operation/user',
              permission: 'operation:user:view',
              icon: 'user-circle',
              children: [
                {
                  id: 24,
                  name: '查看用户',
                  type: 2, // 权限
                  permission: 'operation:user:view',
                  children: [],
                },
                {
                  id: 25,
                  name: '编辑用户',
                  type: 2, // 权限
                  permission: 'operation:user:edit',
                  children: [],
                },
              ],
            },
            {
              id: 26,
              name: '问卷管理',
              type: 1, // 菜单
              path: '/operation/questionnaire',
              permission: 'operation:questionnaire:view',
              icon: 'file-text',
              children: [
                {
                  id: 27,
                  name: '新增问卷',
                  type: 2, // 权限
                  permission: 'operation:questionnaire:add',
                  children: [],
                },
                {
                  id: 28,
                  name: '编辑问卷',
                  type: 2, // 权限
                  permission: 'operation:questionnaire:edit',
                  children: [],
                },
              ],
            },
          ],
        },
      ];
    },

    // 初始化表单数据
    initFormData() {
      if (this.isEdit && this.currentEditData) {
        // 兼容新旧字段名格式
        const menuIds = this.currentEditData.menuIds || this.currentEditData.menuPermissions || [];

        this.formData = {
          roleName: this.currentEditData.name || this.currentEditData.roleName || '',
          roleValue: this.currentEditData.value || this.currentEditData.roleValue || '',
          status: this.currentEditData.status !== undefined ? this.currentEditData.status : 1,
          remark: this.currentEditData.remark || '',
          menuPermissions: [...menuIds],
        };

                // 确保checkedKeys是响应式的
        this.$set(this, 'checkedKeys', [...menuIds]);
      } else {
        this.formData = {
          roleName: '',
          roleValue: '',
          status: 1,
          remark: '',
          menuPermissions: [],
                };
        this.$set(this, 'checkedKeys', []);
      }
    },

    // 初始化树状态
    initTreeState() {
      // 默认展开第一层
      this.expandedKeys = [1, 18]; // 系统管理和运营管理
      this.expandAll = false;

            // 在编辑模式下，重新设置选中的菜单权限
      if (this.isEdit && this.currentEditData) {
        const menuIds = this.currentEditData.menuIds || this.currentEditData.menuPermissions || [];
        this.$set(this, 'checkedKeys', [...menuIds]);

        // 如果有选中的权限，展开相关的父级节点
        if (menuIds.length > 0) {
          this.expandParentNodes();
        }
      }

      this.updateCheckAllState();
    },

    // 展开包含选中节点的父级节点
    expandParentNodes() {
      const expandKeys = new Set([...this.expandedKeys]);

      const findParents = (nodes, parentId = null) => {
        for (const node of nodes) {
          if (this.checkedKeys.includes(node.id)) {
            if (parentId) {
              expandKeys.add(parentId);
            }
          }
          if (node.children && node.children.length > 0) {
            findParents(node.children, node.id);
          }
        }
      };

      findParents(this.menuTreeData);
      this.expandedKeys = Array.from(expandKeys);
    },

    // 更新全选状态
    updateCheckAllState() {
      if (!this.menuTreeData || this.menuTreeData.length === 0) {
        this.checkAll = false;
        return;
      }

      const allKeys = this.getAllTreeKeys(this.menuTreeData);
      const newCheckAll = allKeys.length > 0 && allKeys.every(key => this.checkedKeys.includes(key));
      if (this.checkAll !== newCheckAll) {
        this.checkAll = newCheckAll;
      }
    },

    // 获取所有树节点的key
    getAllTreeKeys(nodes) {
      let keys = [];
      for (const node of nodes) {
        keys.push(node.id);
        if (node.children && node.children.length > 0) {
          keys = keys.concat(this.getAllTreeKeys(node.children));
        }
      }
      return keys;
    },

    // 展开/收起全部
    handleExpandAll() {
      if (!this.menuTreeData || this.menuTreeData.length === 0) {
        this.$message.warning('菜单数据还未加载完成，请稍候再试');
        return;
      }

      this.expandAll = !this.expandAll;
      this.$nextTick(() => {
        if (this.expandAll) {
          this.expandedKeys = [...this.getAllTreeKeys(this.menuTreeData)];
        } else {
          this.expandedKeys = [];
        }
      });
    },

    // 全选/取消全选
    handleCheckAll() {
      if (!this.menuTreeData || this.menuTreeData.length === 0) {
        this.$message.warning('菜单数据还未加载完成，请稍候再试');
        return;
      }

      this.checkAll = !this.checkAll;
      this.$nextTick(() => {
        if (this.checkAll) {
          const allKeys = this.getAllTreeKeys(this.menuTreeData);
          this.checkedKeys = [...allKeys];
        } else {
          this.checkedKeys = [];
        }
      });
    },

    // 保存角色
    async handleSave() {
      try {
        // 表单验证
        const valid = await this.$refs.roleForm.validate();
        if (!valid) return;

        this.saveLoading = true;

                // 确保获取最新的选中菜单ID
        const selectedMenuIds = [...this.checkedKeys];

        // 转换字段名以匹配后端DTO
        const submitData = {
          name: this.formData.roleName,
          value: this.formData.roleValue,
          status: this.formData.status,
          remark: this.formData.remark,
          menuIds: selectedMenuIds
        };

        // 发送保存事件给父组件
        this.$emit('save', submitData);
      } catch (error) {
        this.$message.error('保存角色失败');
      } finally {
        this.saveLoading = false;
      }
    },

    // 关闭抽屉
    handleClose() {
      this.internalVisible = false;
      this.$emit('close');
      // 清除表单验证状态
      this.$nextTick(() => {
        if (this.$refs.roleForm) {
          this.$refs.roleForm.clearValidate();
        }
      });
    },

    // 设置保存状态
    setSaveLoading(loading) {
      this.saveLoading = loading;
    },

    // 处理树选中状态变化
    handleTreeChange(checkedKeys) {
      this.checkedKeys = [...checkedKeys];
      this.formData.menuPermissions = [...checkedKeys];
      this.updateCheckAllState();
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .t-drawer__body {
  padding: 24px;
}

/deep/ .t-form-item {
  margin-bottom: 24px;
}

// 确保抽屉内的下拉菜单有正确的z-index
/deep/ .t-select__popup {
  z-index: 10000 !important;
}

/deep/ .t-popup {
  z-index: 10000 !important;
}

// 确保选择框的样式正确
/deep/ .t-select {
  width: 100%;
}

// 菜单权限样式
.menu-permissions-container {
  width: 100%;
  border: 1px solid #dcdcdc;
  border-radius: 6px;
  padding: 16px;
  background-color: #fafafa;
}

.menu-permissions-toolbar {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e7e7e7;
}

.menu-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 32px;
  color: #999;
}
</style>